package org.jash.shop;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.checkbox.MaterialCheckBox;

import org.jash.shop.entity.CartEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CartActivity extends AppCompatActivity implements CartAdapter.Callback {
    private ListView lv;
    private List<CartEntity.DataDTO> data;
    private CartAdapter adapter;
    private MaterialCheckBox allChecked;
    private TextView totalPrice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        data = new ArrayList<>();
        lv = findViewById(R.id.lv);
        allChecked = findViewById(R.id.all_checked);
        totalPrice = findViewById(R.id.total_price);
        adapter = new CartAdapter(data);
        adapter.setCallback(this);
        lv.setAdapter(adapter);
        update();
        HttpUtils.doGet("http://10.161.9.80:7003/car/getCars", new HashMap<String, String>() {{
                    put("username","1");
                }}, CartEntity.class,
                r -> {
                    if (r.getErrorCode() == 200) {
                        data.addAll(r.getData());
                        adapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(this, r.getErrorMessage(), Toast.LENGTH_SHORT).show();
                    }
                },
                t -> {
                    Toast.makeText(this, t.getMessage(), Toast.LENGTH_SHORT).show();
                });
        allChecked.setOnCheckedChangeListener((buttonView, isChecked) -> {
            data.forEach(d -> d.setChecked(isChecked));
            adapter.notifyDataSetChanged();
        });

        findViewById(R.id.delete).setOnClickListener(v -> {
            data.removeIf(CartEntity.DataDTO::isChecked);
            adapter.notifyDataSetChanged();
        });
    }

    @Override
    public void update() {
        long count = data.stream().filter(CartEntity.DataDTO::isChecked).count();
        if (count == 0) {
            allChecked.setChecked(false);
        } else if (count == data.size()) {
            allChecked.setChecked(true);
        } else {
            allChecked.setCheckedState(MaterialCheckBox.STATE_INDETERMINATE);
        }
        double total = data.stream().filter(CartEntity.DataDTO::isChecked).mapToDouble(d -> d.getCarNum() * d.getGoodsPrice()).sum();
        totalPrice.setText("￥" + total);
    }
}